package com.qxsx.midi.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.me.Mp3PlayerActivity;
import com.qxsx.midi.model.Voice;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.callBackJsonArray;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

/**
 * Created by Joney on 2015/9/6.
 */
public class ExamListAdapter extends BaseAdapter {

    private Context context;

    private List<Voice> lists;

    private File path;//所有音频文件的根目录

    public ExamListAdapter() {

    }

    public ExamListAdapter(Context context, List<Voice> lists) {

        this.context = context;
        this.lists = lists;
        //配置缓存机制
        path = getDiskCacheDir(context, "Music");
        if (!path.exists()) {
            path.mkdirs();
        }

    }

    @Override
    public int getCount() {
        return lists.size();
    }


    @Override
    public Object getItem(int position) {
        return lists.get(position);
    }


    public long getItemId(int position) {
        return position;
    }

    /**
     * 添加数据
     *
     * @param lists
     */
    public void AddData(List<Voice> lists) {
        for (Voice em : lists) {
            this.lists.add(em);
        }
        notifyDataSetChanged();
    }

    /**
     * 清空所有数据
     */
    public void RemoveAll() {
        lists.clear();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        final Voice voice = lists.get(position);
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.exam_list_item, null);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            viewHolder.tv_desc = (TextView) convertView.findViewById(R.id.tv_desc);
            viewHolder.tv_isdownload = (TextView) convertView.findViewById(R.id.tv_isdownload);


            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tv_name.setText(voice.get_name());
        viewHolder.tv_desc.setText(voice.get_desc());

        inItData(voice.get_id(), viewHolder.tv_isdownload);

        convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("_id", voice.get_id());
                intent.putExtra("_title", voice.get_name());
                intent.setClass(context, Mp3PlayerActivity.class);
                context.startActivity(intent);
            }
        });
        return convertView;
    }

    private void inItData(String id, final View view) {

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();

        try {
            object.put("song_id", id);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("514", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                try {
                    if ("200".equals(code.toString())) {
                        JSONObject object = array.getJSONObject(0);
                        String _url = object.getString("song_url");
                        String a[] = _url.split("/");
                        int i = a.length;
                        String fileName = a[i - 1];

                        CheckFile(fileName, _url, view);
                    } else {
                        Log.e("code", code.toString());
                        Log.e("message", code.toString());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 检查本地文件是否存在
     *
     * @param fileName
     */
    public void CheckFile(String fileName, String url, View v) {

        if (fileIsExists(path + "/" + fileName) == false) {
            v.setVisibility(View.GONE);

        } else {
            v.setVisibility(View.VISIBLE);
        }


    }

    /**
     * 判断文件是否存在
     *
     * @param strFile
     * @return
     */
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * 取缓存地址
     *
     * @param context    获取到的系统路径
     * @param uniqueName 对不同类型的数据进行区分而设定的一个唯一值
     * @return
     */
    public File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        // 将系统的路径和唯一值拼接
        return new File(cachePath + File.separator + uniqueName);
    }

    static class ViewHolder {

        private TextView tv_name, tv_isdownload;

        private TextView tv_desc;

    }
}
